package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.bean.Category;
import com.itheima.bean.PageParams;
import com.itheima.common.R;
import com.itheima.mapper.CategoryMapper;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author hebing
 * @version 1.0
 */
//restful风格的controller相当于@Controller+@ResponseBody
@RestController
//接收映射地址
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService cs;

    /**
     * 新增
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> add(@RequestBody Category category) {
        //调用service层进行添加
        int rows = cs.add(category);
        if (rows > 0) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<IPage<Category>> findPage(Long page, Long pageSize) {
        try {
            //调用service进行分页查询
            IPage<Category> iPage = cs.findPage(page, pageSize);
            return R.success(iPage);
        } catch (Exception e) {
            return R.error("分页查询失败");
        }

    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(Long id) {
        System.out.println(id);
        //调用service操作数据库
        int rows = cs.deleteById(id);
        if (rows > 0) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    /**
     * 修改
     *
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        //打印日志
        log.info(category.toString());
        //调用service进行修改
        int rows = cs.update(category);
        //判断
        if (rows > 0) {
            return R.success("修改成功");
        }else{
            return R.error("修改失败");
        }
    }

    /**
     * 根据类型type进行查询
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        try {
            //调用service查询
            List<Category> list = cs.selectByType(type);
            return R.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("下拉框查询失败");
        }

    }
}
